import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from joblib import load
import os


class NN(object):
    def __init__(self):
        model_path = './timing/my_model.keras'
        scaler_path = './timing/scaler.joblib'
        if not os.path.exists(model_path):
            raise FileNotFoundError(f"模型文件 {model_path} 不存在，请检查路径。")
        if not os.path.exists(scaler_path):
            raise FileNotFoundError(f"标准化器文件 {scaler_path} 不存在，请检查路径。")
        self.loaded_model = tf.keras.models.load_model(model_path)
        self.scaler = load(scaler_path)

    def create_dataset(self, df, n_steps):
        """构建数据"""
        X, y = [], []
        for i in range(len(df) - n_steps):
            X.append(df.values[i:i + n_steps])
            y.append(df['count'].values[i + n_steps - 1])  # 假设这里'count'是目标变量，根据实际情况修改
        X = np.array(X)
        y = np.array(y)
        return X, y

    def get_hourly_trend(self):
        """获取每小时趋势（这里只是简单示例，实际应用需完善）"""
        n_steps = 7  # 长度七天，可根据需求调整
        data_path = './timing/scenic_data.csv'
        if not os.path.exists(data_path):
            raise FileNotFoundError(f"数据文件 {data_path} 不存在，请检查路径。")
        df = pd.read_csv(data_path)
        latest_data = df.iloc[-n_steps:].values
        x_values = latest_data[:, :-1]  # 假设最后一列是目标变量，这里取除最后一列外的所有列
        x_values = x_values.reshape(1, n_steps, x_values.shape[1])
        x_values = self.scaler.transform(x_values.reshape(-1, x_values.shape[2])).reshape(1, n_steps, -1)
        prediction = self.loaded_model.predict(x_values)
        predicted_counts = prediction.reshape(-1)
        hourly_trend = [int(count) for count in predicted_counts]  # 转换为整数列表
        return hourly_trend


if __name__ == '__main__':
    try:
        nn = NN()
        hourly_trend = nn.get_hourly_trend()
        print(hourly_trend)
    except Exception as e:
        print(f"程序运行出错: {e}")